const sequelize = require("../sequelize_ins");
const { DataTypes, Model } = require("sequelize");

const core = sequelize.define(
  "question",
  {
    from: DataTypes.INTEGER,
    to: DataTypes.INTEGER,
    text: DataTypes.TEXT,
    zone: DataTypes.INTEGER,
  },
  {
    timestamps: true,
    createdAt: true,
    updatedAt: false,
  }
);

module.exports = {
  core,

  get_struct(n) {
    return {
      id: n.id,
      text: n.text,
      time: n.createdAt,
      from: {
        id: n.from_user.id,
        name: n.from_user.name,
        type: n.from_user.type,
      },
      to: {
        id: n.to_user.id,
        name: n.to_user.name,
        type: n.to_user.type,
      },
    };
  },

  async get_records(query) {
    const include = ["from_user", "to_user"];
    const raw = await this.core.findAll({
      where: { ...query, zone: null },
      include: [...include, { as: "replys", model: this.core, include }],
    });
    return raw.map((n) => {
      const itm = this.get_struct(n);
      itm.replys = n.replys.map(this.get_struct);
      return itm;
    });
  },
};
